package com.example.gmalles.dao.impl;

import com.example.gmalles.dao.ESDao;
import com.example.gmalles.entities.Student;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ESDaoImpl implements ESDao {
    @Autowired
    private JestClient jestClient;


    public List<Student> getStudentList() {
       /*JestClientFactory factory = new JestClientFactory();
       HttpClientConfig conf = new HttpClientConfig.Builder("http://hadoop112:9200").build();
       factory.setHttpClientConfig(conf);
       jestClient = factory.getObject();*/
        String params = "{\n" +
                "  \"query\": {\n" +
                "    \"match_all\": {}\n" +
                "  }\n" +
                "}";
        //查询
        Search search = new Search.Builder(params).addIndex("stu").addType("student").build();
        SearchResult result = null;
        System.out.println(jestClient + " jestClient ");

        try {
            result = jestClient.execute(search);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("total " + result.getTotal() + " score: " + result.getMaxScore());
        System.out.println(result);
        List<Student> list = new ArrayList<>();
        System.out.println("..................................");
        final List<SearchResult.Hit<Student, Void>> hits = result.getHits(Student.class);
        for (SearchResult.Hit<Student, Void> hit : hits) {
            System.out.println("index:" + hit.index + " type:" + hit.type + " score: " + hit.score);
            System.out.println("emp: " + hit.source);
            Student student = new Student();
            student = hit.source;
            list.add(student);
        }

        //关闭
        try {
            jestClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return list;
    }
}

